﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Hisun.Models;
using Hisun.UserControl;
using Hisun.Controllers;
using System.Text;
using System.Collections.Generic;

namespace Hisun.View.DailyDeliverInfo
{
  
    public partial class DailyDeliverInfo:  AbcPageBase
    {
        HisunDBDataContext db = new HisunDBDataContext();
        public string alter;
    
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                

                var CurrentUserCenterId = (from a in db.TAbc_JS_Users where a.操作员ID == Session[ServerVars.sysSessionUserName].ToString() select new { a.责任部门ID }).Single();
                
                DropDownList_CostCenterId.Items.Clear();
                //var myquery = from a in db.TABC_JS_CostCenter                              
                //              select a;
                 tb_date.Text = DateTime.Today.ToString("yyyy-M-d"); 

                FillData2DropDownList(Convert.ToInt32(CurrentUserCenterId.责任部门ID));
            }
        }

       

        //查询当前操作员对应的作业中心列表
        private void FillData2DropDownList(int CenterID)
        {
            ChildCenterList myCenter = new ChildCenterList(CenterID);

            var myCenterFilters = myCenter.CostCenterlist.Where(p => new string[] { "BF", "BG", "BZ" }.Contains(p.类型) && p.停用 == false);
 
            
            foreach (var MylistItem in myCenterFilters)
            {

                    ListItem InsertItem = new ListItem(MylistItem.作业中心名称, MylistItem.作业中心ID.ToString());
                    DropDownList_CostCenterId.Items.Add(InsertItem);
            }

 
        }


        private void FillDailyData(int CostCenterID, string PIPID,DateTime mydate)
        {
            var existdailydata = from a in db.TABC_Daily_ProductInProcessDelivery
                                 where
                                     a.时间 >= mydate.AddDays(-31) && a.时间 <= mydate &&
                                     a.作业中心ID == CostCenterID
                                     && a.中间体ID == PIPID
                                 select a;
            if (existdailydata.Count() < 32)
            {
                for (int day = -31; day <= 0; day++)
                {
                    var check = existdailydata.Where(p => p.时间 == mydate.AddDays(day));
                    if (check.Count() > 0)
                    {
                    }
                    else
                    {

                        TABC_Daily_ProductInProcessDelivery InsertDay = new TABC_Daily_ProductInProcessDelivery();
                        InsertDay.时间 = mydate.AddDays(day);
                        InsertDay.作业中心ID = CostCenterID;
                        InsertDay.中间体ID = PIPID;
                        InsertDay.待返工批数 = 0;
                        InsertDay.待返工批时 = 0;
                        InsertDay.待检批时 = 0;
                        InsertDay.转出批时 = 0;
                        InsertDay.转出批数 = 0;
                        InsertDay.转出数量 = 0; 
                        InsertDay.批号="";
                       // InsertDay.会计期间ID = Application["accountPeriod"].ToString();
                        db.TABC_Daily_ProductInProcessDelivery.InsertOnSubmit(InsertDay);
                        db.SubmitChanges();
                    }

                }
            }
        }

        private void FillDailyData(int CostCenterID, string PIPID)
        {
            FillDailyData(CostCenterID, PIPID, DateTime.Today);
        }


        private void BindMyData(DateTime mydate)
        {
            
            

            int myCenterid = Convert.ToInt32(DropDownList_CostCenterId.SelectedValue);
            string PIPid = DropDownList_PIPId.SelectedValue;
            FillDailyData(myCenterid, PIPid,mydate); //到今天为止32天的空数据加入表格

            var myquery = from a in db.TABC_Daily_ProductInProcessDelivery
                          where a.时间 >= mydate.AddDays(-31) && a.时间 <= mydate
                          && a.作业中心ID == myCenterid && a.中间体ID == PIPid
                          orderby a.时间
                          select new
                          {
                              a.ID,
                              a.时间,
                              a.转出批数,
                              a.转出数量,
                              a.转出批时,
                              批号= a.批号.Length>10 ? a.批号.Substring(0,8)+".." : a.批号
                          }           ;

            GridView_PIPDetail.DataSource = myquery;
            GridView_PIPDetail.DataBind();


            //统计信息

            var sumquery = from a in db.TABC_Daily_ProductInProcessDelivery
                           where a.会计期间ID == getAccoutperiod(mydate)
                           && a.作业中心ID == myCenterid && a.中间体ID == PIPid 
                           group a by new { a.会计期间ID, a.中间体ID, a.作业中心ID } into aa
                           select new
                           {
                               aa.Key.会计期间ID,
                               转出批时 = aa.Sum(p => p.转出批时),
                               转出批数 = aa.Sum(p => p.转出批数),
                               转出数量 = aa.Sum(p => p.转出数量),
                               待返工批时 = aa.Sum(p => p.待返工批时),
                               待返工批数 = aa.Sum(p => p.待返工批数),

                           };
            GridView_Sum.DataSource = sumquery;
            GridView_Sum.DataBind();
                           



        }

        private void BindMyData()
        {
            DateTime mydate = DateTime.Today;
            BindMyData(mydate);
        }
        protected void Button_Query_Click(object sender, EventArgs e)
        {
            DateTime mydate = Convert.ToDateTime(tb_date.Text);
            BindMyData(mydate);
        }
 
        protected void Button_Edit_Command(object sender, CommandEventArgs e)
        {
            int id = int.Parse(e.CommandArgument.ToString());

            var MyEditQuery = ( from a in db.TABC_Daily_ProductInProcessDelivery
                         where a.ID==id
                            select a    ).Single();

            EditPIPId.Value = id.ToString();   //存当前中间体ID，以保证这个保存的时候按ID保存。
            TextBox_Datetime.Text = MyEditQuery.时间.Value.ToString("yyyy-M-d");
            TextBox_Datetime.ReadOnly = true;
            TextBox_转出数量.Text = MyEditQuery.转出数量.ToString();
            TextBox_转出批数.Text = MyEditQuery.转出批数.ToString();
            TextBox_转出批时.Text = MyEditQuery.转出批时.ToString();
            tb_批号.Text = MyEditQuery.批号;
            //TextBox_返工批时.Text = MyEditQuery.待返工批时.ToString();
            //TextBox_返工批数.Text = MyEditQuery.待返工批数.ToString();
            EditFlag.Value = "edit";
            Panel_CenterIdAndPIPid.Enabled = false;
            Panel_EditPanel.Visible = true;
            Panel_GridView.Visible = false;
        }

        protected void Button_Save_Command(object sender, CommandEventArgs e)
        {

            string kjqj = getAccoutperiod(Convert.ToDateTime(TextBox_Datetime.Text));
            int id = int.Parse(EditPIPId.Value);
            var MyEditQuery = (from a in db.TABC_Daily_ProductInProcessDelivery
                               where a.ID == id
                               select a).Single();
            if (MyEditQuery.时间 < DateTime.Today.AddDays(-3))
            {
                alter = "<script>alert('为保证数据准确性，不能修改3天前的数据！！');</script>";
                
               // Response.Write("<script>alert('为保证数据准确性，不能修改一周前的数据！！');</script>");

            }
            else
            {
                MyEditQuery.会计期间ID = kjqj;
                MyEditQuery.转出数量 = Convert.ToDecimal(TextBox_转出数量.Text);
                MyEditQuery.转出批数 = Convert.ToDecimal(TextBox_转出批数.Text);
                MyEditQuery.转出批时 = Convert.ToDecimal(TextBox_转出批时.Text);
                MyEditQuery.批号 = tb_批号.Text.Replace('，',',');
                
                //MyEditQuery.待返工批时 = Convert.ToDecimal(TextBox_返工批时.Text);
                //MyEditQuery.待返工批数 = Convert.ToDecimal(TextBox_返工批数.Text);
                MyEditQuery.操作员ID = Session[ServerVars.sysSessionUserName].ToString();
                MyEditQuery.记录时间 = DateTime.Now;
                db.SubmitChanges();
                alter = "<script>alert('保存成功！！');</script>";
                //Response.Write("<script>alert('保存成功');</script>");
            }
            Panel_EditPanel.Visible = false;
            Panel_GridView.Visible = true;
            Panel_CenterIdAndPIPid.Enabled = true;
            BindMyData();

        }

        private string getAccoutperiod(DateTime it_date)
        {

            var kjqk= (from a in db.TABC_JS_AccountPeriods
                    where a.成本开始日期 <= it_date
                           && a.成本结账日期 >= it_date
                          select a.会计期间ID).Single();
            
            return kjqk;
        }

        protected void Button_Cancel_Command(object sender, CommandEventArgs e)
        {

            Panel_EditPanel.Visible = false;
            Panel_GridView.Visible = true;
            Panel_CenterIdAndPIPid.Enabled = true;
            BindMyData();
        }

      
    }
}
